package cn.tedu.csmall.passport.security;

import cn.tedu.csmall.passport.mappers.AdminMapper;
import cn.tedu.csmall.passport.pojo.vo.AdminLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    AdminMapper adminMapper;


    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        AdminLoginInfoVO admin = adminMapper.getLoginInfoByUsername(s);
        log.debug("{}",admin);
        if(admin == null){
            String message = "登录失败 用户名不存在";
            throw new BadCredentialsException(message);

        }
        ArrayList<GrantedAuthority> authorities = new ArrayList<>();
        for(String permission:admin.getPermissions()){
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission);
            authorities.add(authority);
        }

        AdminDetails adminDetails = new AdminDetails(
                admin.getUsername(), admin.getPassword(), admin.getEnable() == 1,authorities,admin.getId()
        );

//        UserDetails userDetails = User.builder()
//                .username(admin.getUsername())
//                .password(admin.getPassword())
//                .disabled(admin.getEnable() == 0)
//                .accountLocked(false)
//                .accountExpired(false)
//                .credentialsExpired(false)
//                .authorities("暂时给出的价格权限标识")
//                .build();
        log.debug("即将向Spring Security框架返回UserDetails对象：{}", adminDetails);
        return adminDetails;
    }
}
